package com.svs.web.socket;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint("/project/webSocket/{userName}")
@Component
public class WebSocketServer {
	
	private final Logger log = LoggerFactory.getLogger(this.getClass());
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, List<Session>> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }
    //给指定组用户发送信息
    public void sendInfo(String sendName, String message){
        List<Session> sessionList = sessionPools.get(sendName);
        if(CollectionUtils.isEmpty(sessionList)){
        	return;
        }
        for(Session session:sessionList){
        	try {
        		sendMessage(session, message);
        	}catch (Exception e){
        		log.error("给用户发送信息失败",e);
        	}        	
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userName") String userName){
    	userName = userName.trim();//去掉前后空格
    	List<Session> sessionList = sessionPools.get(userName);
    	if(null==sessionList){
    		synchronized (sessionPools) {
    			sessionList = sessionPools.get(userName);
    			if(null==sessionList){
    				sessionList = new ArrayList<>();
    				sessionPools.put(userName, sessionList);
    			}
          }
    	}
    	sessionList.add(session);
        addOnlineCount();
        log.error(userName+"加入,当前人数为" + onlineNum);
        try {
            sendMessage(session, "欢迎" + userName + "加入连接！");
        } catch (IOException e) {
        	log.error(userName+"用户建立连接",e);
        }
    }

    //关闭连接时调用
    @OnClose
    public void onClose(Session session, @PathParam(value = "userName") String userName){
    	userName = userName.trim();//去掉前后空格
    	List<Session> sessionList = sessionPools.get(userName);
    	if(null==sessionList){
    		return;
    	}
    	sessionList.remove(session);
        subOnlineCount();
        log.error(userName+"断开,当前人数为" + onlineNum);
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(Session session,String message) throws IOException{
    	if(StringUtils.isBlank(message)){
    		return;
    	}
    	log.error("接收信息：" + message);
    	JSONObject jsonObject = JSON.parseObject(message);
    	String toUser = jsonObject.getString("toUser");
    	String fromUser = jsonObject.getString("fromUser");
    	String contentText = jsonObject.getString("contentText");
    	String sendBack = jsonObject.getString("sendBack");
    	if(StringUtils.isBlank(fromUser)){//没有来源，直接返回
    		return;
    	}
    	fromUser = fromUser.trim();//去掉前后空格
    	List<Session> sessionList  = new ArrayList<>();
    	if(StringUtils.isBlank(toUser)){//如果发送到的人为空，则判断是否需要回发
    		toUser = fromUser;
    	}
    	if(StringUtils.isNotBlank(sendBack) && sendBack.equals("0")){//只发送给自己
    		sessionList.add(session);
    	}else{//同组的
    		sessionList = sessionPools.get(toUser);    		
    	}
    	if(CollectionUtils.isEmpty(sessionList)){
    		return;
    	}
        for (Session sendSession: sessionList) {
            try {
                sendMessage(sendSession, contentText);
            } catch(Exception e){
            	log.error("接收用户信息后给用户发送指定信息异常",e);
            }
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

}